<template>
	<el-drawer direction="rtl" v-model="dialogVisible" :title="dialogTitle" size="90%">
		<ContentWrap>
			<!-- 搜索工作栏 -->
			<el-form :v-model="form" label-width="120px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="电表名称">
							<el-tag type="info" effect="plain">{{ form.meterName }}</el-tag>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="电表编码">
							<el-tag type="info" effect="plain">
								{{ form.meterNo }}
							</el-tag>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="集中器地址">
							<el-tag type="info" effect="plain">{{ form.meterSerialServerName_ }}</el-tag>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="安装位置">
							<el-tag type="info" effect="plain">{{ form.bindAddresses }}</el-tag>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="保电状态">
							<el-tag type="danger" effect="plain" v-if="form.protectFlag == 1"> 保电中</el-tag>
							<el-tag type="info" effect="plain" v-if="form.protectFlag == 0"> 不保电</el-tag>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="通电状态">
							<dict-tag :type="DICT_TYPE.METER_ELECT_OPEN_STATE" :value="form.elecOpenFlag" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="使用状态">
							<dict-tag :type="DICT_TYPE.METER_USE_STATUS" :value="form.useStatus" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="用电上报">
							<dict-tag :type="DICT_TYPE.METER_REPORT_FLAG" :value="form.reportFlag" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="使用模式">
							<el-tag type="danger" effect="plain" v-if="form.modeFlag == 1"> 后付费</el-tag>
							<el-tag type="info" effect="plain" v-if="form.modeFlag == 0"> 预付费</el-tag>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="最近连接">
							<el-tag type="danger" effect="plain">{{ formatDate(form.lastConnecttime) }}</el-tag>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="账户余额">
							<el-tag type="danger" effect="plain">{{ form.lastBalance }}元</el-tag>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="电费单价">
							<el-tag type="success" effect="plain" v-if="form.hxChargeTplId == null">{{ form.price }}元</el-tag>
							<el-tag type="success" effect="plain" v-else>{{ form.hxChargeTplName }}</el-tag>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="可透支">
							<el-tag type="danger" effect="plain">{{ form.overDraft }}元</el-tag>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="管理人员">
							<el-tag v-for="item in form.authManagerRespVOS" :key="item.authUserId" type="success" effect="plain">
								{{ item.authUserName }}
							</el-tag>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="银联账户">
							<el-tag type="danger" effect="plain" v-if="form.ownMeterConfigRespVO != null">
								{{ form.ownMeterConfigRespVO.memberUserName }}（{{ form.ownMeterConfigRespVO.matCode }}）
							</el-tag>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="账户有效期">
							<el-tag type="danger" effect="plain" v-if="form.ownMeterConfigRespVO != null">
								{{ formatDate(form.ownMeterConfigRespVO.matExpiresTime) }}
							</el-tag>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<el-form label-width="10px" :inline="false">
				<el-form-item>
					<span style="margin-left: 5px; color: green">与电表系统同步后返回的ID值为： {{ form.externalLinkId }}</span>
					<span style="margin-left: 5px; color: red">以下功能均调用电表系统（用于数据查询）</span>
				</el-form-item>
				<el-form-item>
					<span style="margin-left: 5px; color: red">若电表厂家来自弘新能源，部分参数（如负荷限制功率、超负荷延时间等，系统已默认下发过）下发修改需要去厂家后台页面修改</span>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="oper('xfcs')">下发参数</el-button>
					<span style="margin-left: 5px; color: gray">弘新能源电表需要该操作，首次抄表会自动下发参数，如果是三相电表在抄表后，请手动再修改（如负荷限制功率、超负荷延时间等）再次下发</span>
				</el-form-item>
				<el-row>
					<el-col :span="12">
						<el-form-item>
							<el-button type="primary" @click="oper('cb')">抄表</el-button>
							<span style="margin-left: 5px; color: gray">抄表操作将会读取电表上的数据后返回</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item>
							<el-button type="danger" @click="oper('yeql')">余额清零</el-button>
							<span style="margin-left: 5px; color: gray">将电表的余额清零操作</span>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item>
							<el-button type="success" @click="oper('yufufei')">预付费</el-button>
							<span style="margin-left: 5px; color: gray">关闭保电, 用电前需充值,当电表欠费断电</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item>
							<el-button type="danger" @click="oper('houfufei')">后付费</el-button>
							<span style="margin-left: 5px; color: gray">打开保电,电表欠费不断电</span>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item>
							<el-button type="success" @click="oper('bd')">打开保电</el-button>
							<span style="margin-left: 5px; color: gray">打开保电后，在透支情况下可以继续使用</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item>
							<el-button type="danger" @click="oper('qxbd')">关闭保电</el-button>
							<span style="margin-left: 5px; color: gray">关闭保电后，电表余额不足时自动停电</span>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item>
							<el-button type="success" @click="oper('hz')">执行合闸</el-button>
							<span style="margin-left: 5px; color: gray">通电后，电表将通电</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item>
							<el-button type="danger" @click="oper('lz')">执行断电</el-button>
							<span style="margin-left: 5px; color: gray">断电后，电表将不能用电，即断开电路</span>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item>
							<el-button type="primary" @click="oper('dqdj')">读取电价</el-button>
							<span style="margin-left: 5px; color: gray">读取该电表设置的电价</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item>
							<el-button type="danger" @click="oper('xgdj')">修改电价</el-button>
							<span style="margin-left: 5px; color: gray">设置该电表设置的电价</span>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item>
							<el-button type="primary" @click="oper('dqtzje')">读取透支金额</el-button>
							<span style="margin-left: 5px; color: gray">读取该电表设置的透支金额</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item>
							<el-button type="danger" @click="oper('xgtzje')">修改透支金额</el-button>
							<span style="margin-left: 5px; color: gray">设置该电表可透支金额</span>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item v-if="isOpenFromRoom == false">
							<el-button type="danger" @click="oper('dfcz')">电费充值（手动）</el-button>
							<span style="margin-left: 5px; color: gray">进行电费充值（不通过支付）</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item>
							<el-button type="primary" @click="oper('ydcx')">用电查询</el-button>
							<span style="margin-left: 5px; color: gray">查询（外系统）最近N笔用电数据</span>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item>
							<el-button type="primary" @click="oper('czcx')">充值查询-外系统</el-button>
							<span style="margin-left: 5px; color: gray">查询（外系统）最近N笔充值数据</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item>
							<el-button type="primary" @click="oper('czcx2')">充值查询-中微</el-button>
							<span style="margin-left: 5px; color: gray">查询（电表系统）最近N笔充值数据</span>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item>
							<el-button type="primary" @click="oper('czjl')">电表操作记录</el-button>
							<span style="margin-left: 5px; color: gray">查询本系统电表操作记录</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item>
							<el-button type="primary" @click="oper('ydtj')">用电统计</el-button>
							<span style="margin-left: 5px; color: gray">查询（电表系统）用电统计数据</span>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</ContentWrap>
	</el-drawer>

	<FactoryChargeQuery ref="bzlChargeQueryRef" />
	<ChargeQuery ref="chargeQueryRef" />
	<FactoryPowerUseQuery ref="bzlPowerUserQueryRef" />
	<MeterOperLogQuery ref="meterOperLogQueryRef" />
	<MeterUserPowerCount ref="meterUserPowerCountRef" />
	<HxnyPlmChargeTpl ref="hxnyPlmChargeTplRef" @confirm-hxny-plm-charge-tpl="confirmHxnyPlmChargeTpl" />
	<HxnyMeterParam ref="hxnyMeterParamRef" />
</template>
<script lang="ts" setup>
	import { DICT_TYPE } from '@/utils/dict'
	import { formatDate } from '@/utils/formatTime'
	import * as MeterApi from '@/api/zwsj/meter'
	import * as ConfigApi from '@/api/infra/config'
	import { ElNotification } from 'element-plus'
	import FactoryChargeQuery from '@/views/zwsj/meter/FactoryChargeQuery.vue'
	import ChargeQuery from '@/views/zwsj/meter/ChargeQuery.vue'
	import FactoryPowerUseQuery from '@/views/zwsj/meter/FactoryPowerUseQuery.vue'
	import MeterOperLogQuery from '@/views/zwsj/meter/MeterOperLogQuery.vue'
	import MeterUserPowerCount from '@/views/zwsj/meter/MeterUserPowerCount.vue'
	import HxnyPlmChargeTpl from '@/views/zwsj/common/HxnyPlmChargeTpl.vue'
	import HxnyMeterParam from '@/views/zwsj/meter/HxnyMeterParam.vue'

	defineOptions({ name: 'MeterView' })

	const message = useMessage()

	const dialogVisible = ref(false) // 弹窗的是否展示
	const dialogTitle = ref('电表详情') // 弹窗的标题
	const meterIdRef = ref<number>(0)
	const isOpenFromRoom = ref<boolean>(true)

	const form = ref({
		id: 0,
		meterName: undefined,
		meterNo: undefined,
		meterSerialServerName_: undefined,
		authManagerRespVOS: [],
		upayAccountId: undefined,
		accountExpiresTime: undefined,
		externalLinkId: undefined,
		bindAddresses: undefined,
		lastConnecttime: undefined,
		lastBalance: undefined,
		serialServer: {
			id: undefined,
			serialServerName: undefined,
			factoryCode: undefined,
		},
		protectFlag: undefined,
		elecOpenFlag: undefined,
		hxChargeTplId: undefined,
		hxChargeTplName: undefined,
		price: undefined,
		useStatus: undefined,
		reportFlag: undefined,
		ownMeterConfigRespVO: {},
	})

	/** 打开弹窗 */
	const open = async (meterIdT: number) => {
		dialogVisible.value = true
		meterIdRef.value = meterIdT

		isOpenFromRoom.value = false
		getMeter(meterIdT)
	}

	const openByRoomId = async (roomId: number) => {
		dialogVisible.value = true
		dialogTitle.value = '房间电表详情'
		getMeterByRoomId(roomId)
	}
	defineExpose({ open, openByRoomId })

	const getMeterByRoomId = async (roomId: number) => {
		form.value = await MeterApi.getRoomRelaMeter(roomId)
		meterIdRef.value = form.value.id
		if (form.value.serialServer && form.value.serialServer != null) {
			form.value.meterSerialServerName_ = form.value.serialServer.serialServerName
		}
	}
	const factoryCode = ref<number | string>('') // 厂家编码
	const getMeter = async (meterId: number) => {
		form.value = await MeterApi.getMeter(meterId)
		const serialServer = form.value?.serialServer ?? {}
		factoryCode.value = serialServer?.factoryCode ?? ''
		if (form.value.serialServer && form.value.serialServer != null) {
			form.value.meterSerialServerName_ = form.value.serialServer.serialServerName
		}
	}

	const bzlChargeQueryRef = ref()
	const chargeQueryRef = ref()
	const bzlPowerUserQueryRef = ref()
	const meterOperLogQueryRef = ref()
	const meterUserPowerCountRef = ref()
	const hxnyMeterParamRef = ref()
	const oper = async (flag: string) => {
		const meterId: number = meterIdRef.value
		//cb bd qxbd lz hz dqdj xgdj xgtzje ydcx
		switch (flag) {
			case 'cb': {
				//抄表
				message
					.confirm('此操作将读取电表设备上的参数信息, 是否继续?', '抄表')
					.then(() => {
						MeterApi.updateMeterParamByCallReadOut(meterId).then(data => {
							if (data) {
								message.notifySuccess('抄表成功')
								getMeter(meterId)
							}
						})
					})
					.catch(e => {})
				break
			}
			case 'bd': {
				//保电
				message
					.confirm('此操作将会打开电表保电功能, 是否继续?', '保电')
					.then(() => {
						MeterApi.openProtect(meterId).then(data => {
							if (data) {
								message.notifySuccess('保电成功')
								getMeter(meterId)
							}
						})
					})
					.catch(e => {})
				break
			}
			case 'qxbd': {
				//取消保电
				message
					.confirm('此操作将会关闭电表保电功能, 是否继续?', '取消保电')
					.then(() => {
						MeterApi.closeProtect(meterId).then(data => {
							if (data) {
								message.notifySuccess('取消保电成功')
								getMeter(meterId)
							}
						})
					})
					.catch(e => {})
				break
			}
			case 'yufufei': {
				//预付费
				message
					.confirm('配合“不保电”使用，需先充值后使用, 是否继续?', '预付费')
					.then(() => {
						MeterApi.updateMeterModeFlag(meterId, 0).then(data => {
							if (data) {
								message.notifySuccess('改变使用模式[预付费]成功')
								getMeter(meterId)
							}
						})
					})
					.catch(e => {})
				break
			}
			case 'houfufei': {
				//后付费
				message
					.confirm('配合“保电”使用，无限使用, 是否继续?', '后付费')
					.then(() => {
						MeterApi.updateMeterModeFlag(meterId, 1).then(data => {
							if (data) {
								message.notifySuccess('改变使用模式[后付费]成功')
								getMeter(meterId)
							}
						})
					})
					.catch(e => {})
				break
			}
			case 'lz': {
				//断电
				message
					.confirm('此操作将会断开电表的电路（电表将不供电）, 是否继续?', '断电')
					.then(() => {
						MeterApi.updateMeterToLz(meterId).then(data => {
							if (data) {
								message.notifySuccess('断电成功')
								getMeter(meterId)
							}
						})
					})
					.catch(e => {})
				break
			}
			case 'hz': {
				//通电
				message
					.confirm('此操作将会接通电表的电路（电表将供电）, 是否继续?')
					.then(() => {
						MeterApi.updateMeterToHz(meterId).then(data => {
							if (data) {
								message.notifySuccess('通电成功')
								getMeter(meterId)
							}
						})
					})
					.catch(e => {
						ElNotification({ type: 'info', message: e })
					})
				break
			}
			case 'dqdj': {
				//读取电价
				message
					.confirm('此操作将会读取单价, 是否继续?', '读取电价')
					.then(() => {
						MeterApi.getMeterUnitPrice(meterId).then(data => {
							if (data) {
								//判断电表厂家，实现数据展示（可能显示电价，可能显示方案名称）
								if ('0' == data.type) {
									message.notifySuccess('电价价格为' + data.price + '元')
								} else if ('1' == data.type) {
									message.notifySuccess('电价方案为' + data.hxChargeTplName)
								}

								getMeter(meterId)
							}
						})
					})
					.catch(e => {})
				break
			}
			case 'xgdj': {
				//修改电价
				try {
					let priceInfo = await MeterApi.getMeterUnitPrice(meterId)
					if ('0' == priceInfo.type) {
						message
							.confirm('此操作将会设置电费单价, 是否继续?', '修改电价')
							.then(() => {
								ElMessageBox.prompt('请输入电价（一度电）', '提示', {
									confirmButtonText: '确定',
									cancelButtonText: '取消',
									inputPattern: /^[1-9]\d*\.\d+$|^0\.\d+$|^[1-9]\d*$|^0$/,
									inputErrorMessage: '电价不正确',
								}).then(({ value }) => {
									MeterApi.updateMeterUnitPrice({
										id: meterId,
										price: value,
										plmChargeTplId: null,
										plmChargeTplName: null,
									}).then(data => {
										if (data) {
											message.notifySuccess('电价设置成功')
											getMeter(meterId)
										}
									})
								})
							})
							.catch(e => {})
					} else if ('1' == priceInfo.type) {
						openHxnyPlmChargeTpl()
						return false
					}
				} catch {}
				break
			}
			case 'dqtzje': {
				//读取透支金额
				message
					.confirm('此操作将会读取透支金额, 是否继续?', '读取透支金额')
					.then(() => {
						MeterApi.getMeterOverDraft(meterId).then(data => {
							if (data) {
								message.notifySuccess('上一次设置的透支为' + data + '元')
							}
						})
					})
					.catch(e => {})
				break
			}
			case 'xgtzje': {
				//修改透支金额
				message
					.confirm('此操作将会设置透支金额, 是否继续?', '修改透支金额')
					.then(() => {
						ElMessageBox.prompt('请输入可透支的金额', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							inputPattern: /^[1-9]\d*\.\d+$|^0\.\d+$|^[1-9]\d*$|^0$/,
							inputErrorMessage: '金额不正确',
						}).then(({ value }) => {
							MeterApi.updateMeterOverDraft(meterId, value).then(data => {
								if (data) {
									message.notifySuccess('修改透支金额成功')
									getMeter(meterId)
								}
							})
						})
					})
					.catch(e => {})
				break
			}
			case 'yeql': {
				//余额清零
				message
					.confirm('此操作会将电表余额清零, 是否继续?', '余额清零')
					.then(() => {
						MeterApi.clearMeterBalance(meterId).then(data => {
							if (data) {
								message.notifySuccess('余额清零成功')
								getMeter(meterId)
							}
						})
					})
					.catch(e => {})
				break
			}
			case 'dfcz': {
				const data = await ConfigApi.getConfigKey('handle_meter_recharge')
				if ('1' !== data) {
					message.notifyError('暂不支持')
					return false
				}

				//电表进行充值
				message.confirm('此操作将会对电表进行充值, 在充值前，将会进行抄表操作，时间会比较久，是否继续?', '电表进行充值').then(() => {
					//进行抄表操作
					MeterApi.updateMeterParamByCallReadOut(meterId)
						.then(data => {
							if (data) {
								message.notifySuccess('抄表成功')

								//获取余额
								MeterApi.getMeter(meterId).then(meterForm => {
									form.value = meterForm
								})

								ElMessageBox.prompt('该电表余额：(' + form.value.lastBalance + '元)，请输入本次要充值的金额', '提示', {
									confirmButtonText: '确定',
									cancelButtonText: '取消',
									inputPattern: /^[1-9]\d*\.\d+$|^0\.\d+$|^[1-9]\d*$|^0$/,
									inputErrorMessage: '金额不正确',
								})
									.then(({ value }) => {
										MeterApi.recharge(meterId, value).then(data => {
											if (data) {
												message.notifySuccess('充值电费成功')
												getMeter(meterId)
											}
										})
									})
									.catch(e => {})
							}
						})
						.catch(e => {})
				})
				break
			}
			case 'czcx': {
				//充值查询
				bzlChargeQueryRef.value.open(meterId)
				break
			}

			case 'czcx2': {
				//充值查询
				chargeQueryRef.value.open(meterId)
				break
			}

			case 'ydcx': {
				bzlPowerUserQueryRef.value.open(meterId, factoryCode.value)
				break
			}

			case 'czjl': {
				meterOperLogQueryRef.value.open(meterId)
				break
			}

			case 'ydtj': {
				meterUserPowerCountRef.value.open(meterId)
				break
			}

			case 'xfcs': {
				hxnyMeterParamRef.value.open(meterId)
				break
			}
		}
	}

	// 选择电价方案
	const hxnyPlmChargeTplRef = ref()
	const openHxnyPlmChargeTpl = async () => {
		hxnyPlmChargeTplRef.value.open()
	}

	const confirmHxnyPlmChargeTpl = async (tpl: any) => {
		console.info(tpl)
		MeterApi.updateMeterUnitPrice({
			id: meterIdRef.value,
			price: null,
			plmChargeTplId: tpl.id,
			plmChargeTplName: tpl.name,
		}).then(data => {
			if (data) {
				message.notifySuccess('电价方案设置成功')
				getMeter(meterIdRef.value)
			}
		})
	}
</script>
